#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用户认证API
"""

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.models.permission_simple import User
from app.schemas.user import UserLogin, LoginResponse, UserResponse
from app.services.auth import authenticate_user, create_access_token, verify_token, get_password_hash

router = APIRouter()
security = HTTPBearer()


def get_current_user_id(credentials: HTTPAuthorizationCredentials = Depends(security), db: Session = Depends(get_db)) -> int:
    """获取当前用户ID的依赖注入"""
    token_data = verify_token(credentials.credentials)
    if not token_data:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的认证令牌",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return token_data["uid"]


@router.post("/login")
async def login(user_credentials: UserLogin, db: Session = Depends(get_db)):
    """用户登录"""
    print(f"收到登录请求: username={user_credentials.username}")
    
    user = authenticate_user(db, user_credentials.username, user_credentials.password)
    if not user:
        # 检查用户是否存在
        existing_user = db.query(User).filter(User.username == user_credentials.username).first()
        if not existing_user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户不存在",
                headers={"WWW-Authenticate": "Bearer"},
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户名或密码错误",
                headers={"WWW-Authenticate": "Bearer"},
            )
    
    access_token = create_access_token(data={"sub": user.username, "uid": user.id})
    
    return {
        "code": 200,
        "message": "登录成功",
        "data": {
            "uid": user.id,
            "username": user.username,
            "name": user.name,
            "token": access_token
        }
    }

@router.get("/me")
async def get_current_user(current_user_id: int = Depends(get_current_user_id), db: Session = Depends(get_db)):
    """获取当前用户信息"""
    user = db.query(User).filter(User.id == current_user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    return {
        "code": 200,
        "message": "success",
        "data": {
            "id": user.id,
            "username": user.username,
            "name": user.name,
            "role_id": user.role_id,
            "role_name": user.role.name if user.role else None,
            "is_active": user.is_active,
            "created_at": user.created_at.isoformat() if user.created_at else None
        }
    }

@router.post("/register")
async def register(
    user: UserLogin,
    db: Session = Depends(get_db)
):
    """用户注册（测试用）"""
    # 检查用户名是否已存在
    existing_user = db.query(User).filter(User.username == user.username).first()
    if existing_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户名已存在"
        )
    
    # 创建新用户
    hashed_password = get_password_hash(user.password)
    db_user = User(
        username=user.username,
        password=hashed_password,
        name=user.username,  # 默认使用用户名作为姓名
        role_id=4  # 默认访客角色
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    
    return {"message": "用户注册成功", "user_id": db_user.id}

def get_current_user_id(credentials: HTTPAuthorizationCredentials = Depends(security), db: Session = Depends(get_db)) -> int:
    """获取当前用户ID的依赖注入"""
    token_data = verify_token(credentials.credentials)
    if not token_data:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的认证令牌",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return token_data["uid"]